package com.joesem.sale.client.widget.popup

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.PopupSingleListBinding
import com.joesem.sale.client.network.data.SingleListMode
import com.joesem.sale.client.utils.click

class SingleListPopup(val context: Context) {

    private val up: PopupWindow = PopupWindow()

    fun show(
        view: View,
        data: List<SingleListMode>,
        default: SingleListMode? = null,
        selected: (SingleListMode) -> Unit
    ) {
        up.apply {
            contentView = PopupSingleListBinding.inflate(LayoutInflater.from(context)).apply {
                val adapter = object :
                    BaseQuickAdapter<SingleListMode, BaseViewHolder>(R.layout.item_single_text) {
                    var selectedItem: SingleListMode? = null
                    override fun convert(holder: BaseViewHolder, item: SingleListMode) {
                        holder.setText(R.id.tv_title, item.name)
                        holder.getView<TextView>(R.id.tv_title).apply {
                            selectedItem?.let {
                                isSelected = item.name == it.name && item.code == it.code
                            }
                            click {
                                selectedItem = item
                                notifyDataSetChanged()
                                selected.invoke(item)
                                dismiss()
                            }
                        }
                    }
                }
                adapter.selectedItem = default
                adapter.setList(data)
                rvContent.adapter = adapter
            }.root
            width = ViewGroup.LayoutParams.WRAP_CONTENT
            height = ViewGroup.LayoutParams.WRAP_CONTENT
            isOutsideTouchable = true
        }.showAsDropDown(view, 0, 0, Gravity.BOTTOM)
    }
}

fun optionSingleText(
    view: View,
    defaultSelected: SingleListMode? = null,
    data: List<SingleListMode>,
    selected: (SingleListMode) -> Unit
) {
    SingleListPopup(view.context).show(
        view,
        data = data,
        defaultSelected, selected
    )
}